package com.luobd.bpm.business.process.service.impl;

import com.luobd.bpm.business.process.service.IProcessInstanceService;
import com.luobd.bpm.command.CustomStartProcessInstanceCmd;
import com.luobd.bpm.common.CurrentRequestHolder;
import com.luobd.bpm.common.ResponseData;
import org.activiti.engine.*;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Primary
public class ProcessInstanceServiceImpl implements IProcessInstanceService {


    @Autowired
    private RuntimeService runtimeService;


    @Autowired
    private HistoryService historyService;


    @Autowired
    private ManagementService managementService;




    @Override
    public ResponseData<Boolean> revoke(String processInstanceId) {
        //根据processInstanceId查询流程实例
        ProcessInstance processInstance =
                runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).
                        singleResult();
        if (processInstance == null) {
            throw new ActivitiObjectNotFoundException("编号为" + processInstanceId + "的 流程实例不存在。", ProcessInstance.class);
        }
        //非流程发起者不能撤销流程

        String userInfoId = String.valueOf(CurrentRequestHolder.get().getUserInfoId());
        if (!processInstance.getStartUserId().equals(userInfoId)) {
            throw new ActivitiException("非流程发起者不能撤销流程。");
        }

        //查询流程变量
        Map<String,Object> variables = runtimeService.getVariables(processInstanceId);
        //删除流程实例
        runtimeService.deleteProcessInstance(processInstanceId, "");
        //删除历史流程实例
        historyService.deleteHistoricProcessInstance(processInstanceId);
        //重建流程
                managementService.executeCommand(new CustomStartProcessInstanceCmd<>(processInstance.getProcessDefinitionKey(),
                        processInstance.getProcessDefinitionId(), processInstance.getBusinessKey(),
                        variables,processInstance.getId(), processInstance.getTenantId(),processInstance.getName()));
        return ResponseData.success(Boolean.TRUE);
    }
}
